package com.yuanfeng.base.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yuanfeng.base.dto.QueryResultDTO;
import com.yuanfeng.base.dto.WxChatIdParamDTO;
import com.yuanfeng.base.entity.BaseWxLiveHostEntity;
import com.yuanfeng.base.mapper.BaseWxLiveHostMapper;
import com.yuanfeng.base.service.BaseWxLiveHostService;
import com.yuanfeng.base.utils.AccessTokenUtil;
import com.yuanfeng.base.vo.*;
import com.yuanfeng.commoms.config.YFConfig;
import com.yuanfeng.commoms.constant.CommonStatusEnum;
import com.yuanfeng.commoms.constant.CommonType;
import com.yuanfeng.commoms.dto.userms.UserTokenBeanDTO;
import com.yuanfeng.commoms.exception.BizCodeEnume;
import com.yuanfeng.commoms.util.ParseMapUtils;
import com.yuanfeng.commoms.util.ParseTokenUtils;
import com.yuanfeng.commoms.util.RedisUtil;
import com.yuanfeng.commoms.util.ResponseResult;
import com.yuanfeng.commoms.util.querypage.PageHelper;
import com.yuanfeng.commoms.util.querypage.PageUtils;
import com.yuanfeng.commoms.util.querypage.Query;
import com.yuanfeng.commoms.vo.user.UserInfoVO;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestClientException;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @ClassName BaseWxLiveHostServiceImpl
 * @Description
 * @Author liulh
 * @Date 2023/7/24 13:38
 * @Version 1.0
 **/
@Service
public class BaseWxLiveHostServiceImpl extends ServiceImpl<BaseWxLiveHostMapper, BaseWxLiveHostEntity>
        implements BaseWxLiveHostService {

    @Resource
    private RestTemplate restTemplate;

    @Override
    public ResponseResult queryLiveHostState(UserTokenBeanDTO param) {
        UserInfoVO userInfo = ParseTokenUtils.getUserInfoByToken(param.getToken());
        if (null == userInfo) {
            return ResponseResult.fail(BizCodeEnume.TOKEN_IS_ILLEGAL.getCode(), BizCodeEnume.TOKEN_IS_ILLEGAL.getMsg());
        }
        QuLiveHostStateResultVO result = this.baseMapper.queryLiveHostState(Integer.valueOf(userInfo.getShopId()));
        if (null != result) {
            return ResponseResult.success(1, "请求成功", result);
        }
        return ResponseResult.success(1, "未添加主播", result);
    }

    @Override
    public ResponseResult applyForHost(Map<String, Object> param) {
        String token = param.get("token").toString();
        UserInfoVO userInfo = ParseTokenUtils.getUserInfoByToken(token);
        if (null == userInfo) {
            return ResponseResult.fail(BizCodeEnume.TOKEN_IS_ILLEGAL.getCode(), BizCodeEnume.TOKEN_IS_ILLEGAL.getMsg());
        }

        BaseWxLiveHostEntity applyMap = new BaseWxLiveHostEntity();
        applyMap.setUserId(userInfo.getUserId());
        applyMap.setShopId(Integer.valueOf(userInfo.getShopId()));
        applyMap.setOperation(1);
        applyMap.setWechatId(param.get("wxChatId").toString());
        applyMap.setState(4);
        applyMap.setHeadPortrait(userInfo.getUserAvatar());

        QueryWrapper<BaseWxLiveHostEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("wechat_id",param.get("wxChatId"));
        Integer repetition = this.baseMapper.selectCount(queryWrapper);
        if (repetition > 0) {
            return ResponseResult.fail(2, "此微信已经申请，请不要重复提交");
        }
        Integer integer = this.baseMapper.insert(applyMap);
        if (null != integer && integer == 1) {
            return ResponseResult.success(1, "申请成功", integer);
        }
        return ResponseResult.fail(2, "申请失败");
    }

    @Override
    public ResponseResult upWeChatId(Map<String, Object> param) {
        String host = "https://api.weixin.qq.com";
        String accessToken = AccessTokenUtil.queryAccessToken();
        String delpath = "/wxaapi/broadcast/role/deleterole?access_token=" + accessToken;
//        https://api.weixin.qq.com/wxaapi/broadcast/role/getrolelist?access_token=
        String getpath = "https://api.weixin.qq.com/wxaapi/broadcast/role/getrolelist?access_token=ACCESSTOKEN&keyword=KEYWORD&role=ROLE";
        String token = param.get("token").toString();
        String wxChatId = param.get("wechatId").toString();
        UserInfoVO userInfo = ParseTokenUtils.getUserInfoByToken(token);
        if (null == userInfo) {
            return ResponseResult.fail(BizCodeEnume.TOKEN_IS_ILLEGAL.getCode(), BizCodeEnume.TOKEN_IS_ILLEGAL.getMsg());
        }
        QueryResultVO queryResult = null;
        QueryWrapper<BaseWxLiveHostEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("shop_id",userInfo.getShopId());
        BaseWxLiveHostEntity wxLiveHosts = this.baseMapper.selectOne(queryWrapper);
        if (null == wxLiveHosts) {
            return ResponseResult.fail(2, "请先设置微信号");
        }
        BaseWxLiveHostEntity hostEntity = new BaseWxLiveHostEntity();
        hostEntity.setWechatId(wxChatId);
        hostEntity.setId(wxLiveHosts.getId());
        hostEntity.setState(4);
        hostEntity.setOperation(0);
        hostEntity.setHoststate(2);
        if (wxLiveHosts.getState() == 1 || wxLiveHosts.getState() == 6) {
            queryResult = new QueryResultVO();
            queryResult.setRole(2);
            queryResult.setUsername(wxChatId);
            getpath = getpath.replace("ACCESSTOKEN", accessToken).replace("KEYWORD", wxChatId).replace("ROLE", "2");
            QuroleResultVO forObject = restTemplate.getForObject(getpath, QuroleResultVO.class);
            if (forObject.getList().size() != 0) {
                SetRoleReponseResultVO result = restTemplate.postForObject(host + delpath, queryResult, SetRoleReponseResultVO.class);
                if (result.getErrcode() == 0) {
                    Integer integer = this.baseMapper.updateById(hostEntity);
                    if (1 == integer) {
                        return ResponseResult.success(integer);
                    }
                }
                return ResponseResult.fail(CommonStatusEnum.FAIL.getCode(),BizCodeEnume.OPERATION_FAILED.getMsg());
            }
            Integer integer = this.baseMapper.updateById(hostEntity);
            if (1 == integer) {
                return ResponseResult.success(integer);
            }
        }
        Integer integer = this.baseMapper.updateById(hostEntity);
        if (1 == integer) {
            return ResponseResult.success(integer);
        }
        return ResponseResult.fail(CommonStatusEnum.FAIL.getCode(),BizCodeEnume.OPERATION_FAILED.getMsg());
    }

    @Override
    public ResponseResult queryLiveRoomsByName(Map<String, String> param) {
        try {
            List<RoomInfoVO> room_info = new ArrayList<>();
            for (int i = 1; i >0 ; i++) {
                String accessToken = AccessTokenUtil.queryAccessToken();
                String host = "https://api.weixin.qq.com";
                String addpath = "/wxa/business/getliveinfo?access_token="+accessToken;
                Map<String, Integer> map = new HashMap<>();
                map.put("start",i-1);
                map.put("limit",20);
                LiveStudioResultVO results= restTemplate.postForObject(host + addpath, map, LiveStudioResultVO.class);
                if (results.getRoom_info().size() > 0) {
                    for (RoomInfoVO roomInfo : results.getRoom_info()) {
                        room_info.add(roomInfo);
                    }
                }else {
                    break;
                }
            }
            if (null != param && null != param.get("name")) {
                 List<RoomInfoVO> boys = room_info.stream().filter(r-> r.getRoomid().equals(param.get("name"))).collect(Collectors.toList());
                 return ResponseResult.success(boys);
            }
        } catch (RestClientException e) {
            e.printStackTrace();
        }
        return ResponseResult.fail(BizCodeEnume.SYSTEM_ERROR.getCode(),BizCodeEnume.SYSTEM_ERROR.getMsg());
    }


    @Override
    public ResponseResult queryLiveRooms(PageHelper param) {
        param.setCurrentPage((param.getStart() - 1) * param.getLimit());
        String accessToken = AccessTokenUtil.queryAccessToken();

        String host = "https://api.weixin.qq.com";
        String addpath = "/wxa/business/getliveinfo?access_token="+accessToken;

        Map<String, Integer> map = new HashMap<>();
        map.put("start", param.getCurrentPage());
        map.put("limit",param.getLimit());

        String result= restTemplate.postForObject(host + addpath, map, String.class);
        return ResponseResult.success(result);
    }

    @Override
    public ResponseResult stopLive(Map<String, Object> param) {
        UserInfoVO userInfo = ParseTokenUtils.getPlatformUser(param.get("token").toString());
        if (null != userInfo) {
            this.baseMapper.update(null,new LambdaUpdateWrapper<BaseWxLiveHostEntity>()
                           .eq(BaseWxLiveHostEntity::getId,param.get("id").toString())
                           .set(BaseWxLiveHostEntity::getOperation, CommonType.commonStatus.NO.getCode())
                           .set(BaseWxLiveHostEntity::getState,CommonType.liveGoodsVerify.APPROVED.getCode())
                           .set(BaseWxLiveHostEntity::getHoststate,param.get("hostState").toString()));
            return ResponseResult.success(BizCodeEnume.OPERATION_SUCCESSFUL);
        }
        return ResponseResult.fail(BizCodeEnume.TOKEN_IS_ILLEGAL);
    }

    @Override
    public ResponseResult platformApplyForHost(WxChatIdParamDTO param) {
        ResponseResult rr = new ResponseResult();
        String token = param.getToken();
        boolean isExistToken = RedisUtil.exists(YFConfig.YF_PLATFORM_TOKEN_USER + token);
        if (isExistToken) {

            if (param.getState() == 3 ) {
                Integer integer = this.baseMapper.update(null,new LambdaUpdateWrapper<BaseWxLiveHostEntity>()
                                 .eq(BaseWxLiveHostEntity::getId,param.getId())
                                 .set(BaseWxLiveHostEntity::getOperation, CommonType.commonStatus.NO.getCode())
                                 .set(BaseWxLiveHostEntity::getState,param.getState())
                                 .set(BaseWxLiveHostEntity::getCause,param.getCause()));
                if (integer>0) {
                    return ResponseResult.success(BizCodeEnume.OPERATION_SUCCESSFUL);
                }
            }

            String host = "https://api.weixin.qq.com";
            String accessToken = AccessTokenUtil.queryAccessToken();
            String addpath = "/wxaapi/broadcast/role/addrole?access_token=" + accessToken;
            //https://api.weixin.qq.com/wxaapi/broadcast/role/deleterole?access_token=
            String delpath = "/wxaapi/broadcast/role/deleterole?access_token=" + accessToken;
            QueryResultDTO queryResult = null;
            // 如果是添加操作主播
            if (param.getOperation() == 1) {
                queryResult = new QueryResultDTO();
                queryResult.setRole(2);
                queryResult.setUsername(param.getWxChatId());
                SetRoleReponseResultVO result = restTemplate.postForObject(host + addpath, queryResult, SetRoleReponseResultVO.class);
                if (result.getErrcode() == 0) {
                    rr.setCode(CommonStatusEnum.SUCCESS.getCode());
                    rr.setMessage("主播角色设置成功");
                    Integer integer = this.baseMapper.updateHostState(param.getId(), 1,"微信审核通过");
                    if (1 == integer) {
                        rr.setCode(CommonStatusEnum.SUCCESS.getCode());
                        rr.setData(integer);
                    }
                } else if (result.getErrcode() == 40001) {
                    rr.setData(result.getMsg());
                    rr.setMessage("AccessToken过期或者失效请联系管理员");
                    Integer integer =  this.baseMapper.updateHostState(param.getId(), 3,"微信审核失败");
                    if (1 == integer) {
                        rr.setCode(CommonStatusEnum.SUCCESS.getCode());
                    }
                } else if (result.getErrcode() == 40002) {
                    rr.setData(result.getMsg());
                    rr.setMessage("此用户未实名，请先实名认证");
                    Integer integer =  this.baseMapper.updateHostState(param.getId(), 3,"微信审核失败，用户未实名");
                    if (1 == integer) {
                        rr.setCode(CommonStatusEnum.SUCCESS.getCode());
                    }
                } else if (result.getErrcode() == 40003) {
                    rr.setData(result.getMsg());
                    rr.setMessage("添加角色达到上限");
                    Integer integer =  this.baseMapper.updateHostState(param.getId(), 3,"微信审核失败，添加角色上限联系管理员");
                    if (1 == integer) {
                        rr.setCode(CommonStatusEnum.SUCCESS.getCode());
                    }
                } else if (result.getErrcode() == 40004) {
                    rr.setData(result.getMsg());
                    rr.setMessage("重复添加角色");
                    Integer integer =  this.baseMapper.updateHostState(param.getId(), 3,"微信审核失败，重复添加");
                    if (1 == integer) {
                        rr.setCode(CommonStatusEnum.SUCCESS.getCode());
                    }
                } else if (result.getErrcode() == 20002){
                    rr.setData(result.getMsg());
                    rr.setMessage("入参不正确");
                    Integer integer =  this.baseMapper.updateHostState(param.getId(), 3,"微信审核失败");
                    if (1 == integer) {
                        rr.setCode(CommonStatusEnum.SUCCESS.getCode());
                    }
                } else {
                    rr.setData(result.getMsg());
                    rr.setMessage("微信审核失败");
                    Integer integer =  this.baseMapper.updateHostState(param.getId(), 3,"微信审核失败，未知原因，联系管理员");
                    if (1 == integer) {
                        rr.setCode(CommonStatusEnum.SUCCESS.getCode());
                    }
                }
                //删除
            } else {
                queryResult = new QueryResultDTO();
                queryResult.setRole(2);
                queryResult.setUsername(param.getWxChatId());
                SetRoleReponseResultVO result = restTemplate.postForObject(host + delpath, queryResult, SetRoleReponseResultVO.class);
                if (result.getErrcode() == 0) {
                    rr.setMessage("删除成功");
                    Integer integer =  this.baseMapper.deleteById(param.getId());
                    if (1 == integer) {
                        rr.setCode(CommonStatusEnum.SUCCESS.getCode());
                        rr.setData(integer);
                    }
                } else {
                    rr.setCode(CommonStatusEnum.SUCCESS.getCode());
                    rr.setMessage("删除失败");
                    rr.setData(result.getMsg());
                }

            }
        } else {
            rr.setCode(10086);
            rr.setMessage(BizCodeEnume.TOKEN_IS_INVALID.getMsg());
        }
        return rr;
    }

    @Override
    public ResponseResult queryHosts(WxChatIdParamDTO param) {
        UserInfoVO userInfo = ParseTokenUtils.getPlatformUser(param.getToken());
        if (null != userInfo) {
            try {
                //将对象转换为map
                Map data = ParseMapUtils.beanToMap(param);
                //分页查询数据
                IPage<WxHostsVO> page = this.baseMapper.queryHosts(new Query<WxHostsVO>().getPage(data), param);

                return ResponseResult.success(PageUtils.getPage(page));
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }
        }
        return ResponseResult.fail(BizCodeEnume.TOKEN_IS_ILLEGAL);
    }
}
